import mongoose, { Document, Schema } from 'mongoose';

export interface IPermissionSchema extends Document {
    type: 'button' | 'menu';
    name?: string; // sort:read:all 
    createdBy: mongoose.Schema.Types.ObjectId,
    updatedBy: mongoose.Schema.Types.ObjectId,
    pageId: mongoose.Schema.Types.ObjectId,
    roleId?: mongoose.Schema.Types.ObjectId,
}

const permissionSchema = new Schema<IPermissionSchema>({
    type: {
        type: String,
        enum: ['button', 'menu'],
        required: [true, '权限类型是必填项'],
        trim: true
    },
    pageId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Menu',
    },
    roleId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Role',
    },
    name: {
        type: String,
        required: [true, '权限名称是必填项'],
        trim: true
    },
    createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    updatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
}, {
    timestamps: true // 自动添加 createdAt 和 updatedAt
});

// 创建索引
permissionSchema.index({ createdAt: -1 });

// 虚拟字段（不存储在数据库中）
permissionSchema.virtual('displayName').get(function () {
    return `${this.name} (${this.type == 'button' ? '按钮' : '菜单'})`;
});

// 实例方法
permissionSchema.methods.toJSON = function () {
    const permission = this.toObject();
    return permission;
};


export const PermissionModel = mongoose.model<IPermissionSchema>('Permission', permissionSchema);
